import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
// import { compareSync } from 'bcryptjs';

import { ToolsService } from '../../utils/tools.service';
import { RedisCacheService } from 'src/component/redis/redis-cache.service';
import { UsersEntity } from 'src/module/user/entities/user.entity';
import { AccountEntity } from 'src/module/account/entities/account.entity';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(UsersEntity)
    private readonly usersRepository: Repository<UsersEntity>,
    @InjectRepository(AccountEntity)
    private readonly accountRepository: Repository<AccountEntity>,
    private readonly jwtService: JwtService,
    private readonly redisService: RedisCacheService,
  ) {}

  async validateUser(userinfo): Promise<any> {
    const { accountnumer, password } = userinfo;
    const account = await this.accountRepository
      .createQueryBuilder('AccountEntity')
      .where('AccountEntity.accountnumer = :accountnumer', { accountnumer })
      .leftJoinAndSelect('AccountEntity.user', 'user')
      .select(['AccountEntity', 'user'])
      .addSelect('user.password')
      .getOne();
    // const user = await this.usersRepository.findOne({
    //   where: { username: accountnumer },
    //   select: ['username', 'password', 'id'],
    // });
    if (!account.user) ToolsService.fail('用户名或密码不正确');
    //使用bcryptjs验证密码
    if (password != account.user.password) {
      ToolsService.fail('用户名或密码不正确');
    }
    return account.user;
  }
  async login(user: any): Promise<any> {
    const payload = { username: user.username, id: user.id }; // 把信息存在token
    const access_token = this.jwtService.sign(payload);
    await this.redisService.set(
      `user-token-${payload.id}`,
      access_token,
      60 * 60 * 24,
    ); //在这里使用redis
    return access_token;
  }
}
